package cate.game.role.pvp.teampvp.msg;

import cate.common.table.d.GDFunc;
import cate.game.client.msg.MsgConfig;
import cate.game.client.msg.MsgOutput;
import cate.game.client.msg.id.MsgIdBTeamPvp;
import cate.game.pvp.teampvp.dto.SynTeamPvpTeamData;
import cate.game.pvp.teampvp.dto.TeamPvpPlayerSimpleData;
import cate.game.pvp.teampvp.dto.TeamPvpTeamData;
import cate.game.role.Role;
import cate.game.role.fight.FuncPosition;
import cate.game.role.fight.Position;
import cate.game.role.pvp.teampvp.MyTeamPvp;
import easy.java.dev.note.NoteField;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;


import java.util.List;

import static cate.common.table.d.GDFunc.ADVENTURE;

public class TeamPvpDataResp implements MsgOutput {
    @NoteField("组队竞技数据")
    public MyTeamPvp mydata;
    public TeamPvpTeamData teamData;

    public TeamPvpDataResp() {

    }

    public TeamPvpDataResp(Role role) {
        this.mydata = role.getPvp().teamPvp;
        if (role.getFight().funcPositions.get(GDFunc.TEAM_PVP) == null
                || role.getFight().funcPositions.get(GDFunc.TEAM_PVP).positions.isEmpty()) {
            Position position = role.getFight().getPosition(ADVENTURE);
            if (position != null) {
                FuncPosition funcPosition = new FuncPosition();
                funcPosition.init();
                funcPosition.funcId = GDFunc.TEAM_PVP;
                funcPosition.positions.add(position.copy());
                role.getGame().fight.position.updatePosition(role, funcPosition);
            }
        }
        SynTeamPvpTeamData synTeamData = role.getGame().pvp.teamPvp.syncTeamData(role);
        if (synTeamData != null) {
            this.teamData = synTeamData.team;
            TeamPvpPlayerSimpleData mySimpleData = findMyData(this.teamData.members, role.getUid());
            if (mySimpleData != null) {
                mydata.challengeTimes = mySimpleData.challengeTimes;
            }
            if (synTeamData.hasRedPoint) {
                role.sendNow(new TeamPvpRedPointResp());
            }
        }
    }

    private TeamPvpPlayerSimpleData findMyData(List<TeamPvpPlayerSimpleData> members, String roleUid) {
        if (CollectionUtils.isEmpty(members)) {
            return null;
        }
        return members.stream().filter(e -> StringUtils.equals(e.base.uid, roleUid)).findAny().orElse(null);
    }

    public TeamPvpDataResp(Role role, TeamPvpTeamData team) {
        this.mydata = role.getPvp().teamPvp;
        this.teamData = team;
        TeamPvpPlayerSimpleData mySimpleData = findMyData(this.teamData.members, role.getUid());
        if (mySimpleData != null) {
            mydata.challengeTimes = mySimpleData.challengeTimes;
        }
    }

    @Override
    public MsgConfig conf() {
        return MsgIdBTeamPvp.DATA_RESP;
    }
}
